<template>
  <div id="space-tag-analyze">
    <a-card title="图库标签分布" style="width: 100%">
      <v-chart :option="options" style="height: 320px; max-width: 100%;" :loading="loading" />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, ref, watchEffect} from 'vue'
import { getSpaceTagAnalyzeUsingPost} from '@/api/spaceAnalyzeController'
import { message } from 'ant-design-vue'
import VChart from "vue-echarts";
import "echarts";
import 'echarts-wordcloud'

interface Props {
  queryAll?: boolean
  queryPublic?: boolean
  spaceId?: number
}

const props = withDefaults(defineProps<Props>(), {
  // 默认为false，这样如果单独分析某空间只需要传spaceId
  queryAll: false,
  queryPublic: false,
})

// 接受图表数据
const dataList = ref<API.SpaceTagAnalyzeResponse[]>([])
const loading = ref<boolean>(true) // 默认为true，加载

/**
 * 加载数据
 */
const fetchData = async () => {
  loading.value = true
  const res = await getSpaceTagAnalyzeUsingPost({
    queryAll: props.queryAll,
    queryPublic: props.queryPublic,
    spaceId: props.spaceId,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  // 加载完毕结束加载状态
  loading.value = false
}

/**
 * 监听变量，改变时触发数据的重新加载
 * 只要有任何一个值发生变化，都会重新执行封装的函数
 */
watchEffect(() => {
  fetchData()
})

// 图表内容参数
const options = computed(() => {
  const tagData = dataList.value.map((item) => ({
    name: item.tag,
    value: item.count,
  }))

  return {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => `${params.name}: ${params.value} 次`,
    },
    series: [
      {
        type: 'wordCloud',
        gridSize: 10,
        sizeRange: [12, 50], // 字体大小范围
        rotationRange: [-90, 90],
        shape: 'circle',
        textStyle: {
          color: () =>
            `rgb(${Math.round(Math.random() * 255)}, ${Math.round(
              Math.random() * 255,
            )}, ${Math.round(Math.random() * 255)})`, // 随机颜色
        },
        data: tagData,
      },
    ],
  }
})

</script>

<style scoped></style>
